<?php
/**
 * Created by PhpStorm.
 * User: Yan
 * Date: 2017/9/26
 * Time: 13:54
 */
namespace App\Http\Controllers\API\Teacher;
use App\Http\Controllers\Controller;
use App\Models\Teacher;
use Illuminate\Http\Request;

class TeacherController extends Controller
{
    public function index(Teacher $request)
    {
        $queryString = $request->get('query', '');
        $models = Teacher::query()
            ->where('teachers_name', 'like', '%' . $queryString . '%')
            ->orWhere('teachers_code', 'like', '%' . $queryString . '%')
            ->paginate();
        return $models;
    }


    /**
     * 添加学生
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new Teacher();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(Teacher $Teacher, Request $request)
    {
        $Teacher->fill($request->all());
        if ($Teacher->save()) {
            return $Teacher;
        } else {
            return response($Teacher->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }


    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = Teacher::findOrFail($id);
        return $model;
    }
}